package org.spiderdesign.core.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.spiderdesign.core.common.Department;
import org.spiderdesign.core.common.Position;
import org.spiderdesign.core.mapper.EmployeeMapper;
import org.spiderdesign.core.model.Employee;
import org.spiderdesign.core.model.SpiderFlow;
import org.spiderdesign.core.model.vo.EmployeeVO;
import org.spiderdesign.core.utils.MD5Util;
import org.spiderdesign.model.JsonBean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmployeeService extends ServiceImpl<EmployeeMapper, Employee> {
    @Resource
    private EmployeeMapper employeeMapper;

    
    //登录接口
    public JsonBean<Void> login(HttpServletRequest request, HttpServletResponse response, String loginName, String password) {
        //非空校验
        if(StringUtils.isEmpty(loginName)) {
            return new JsonBean<>(0,"请填写登录账号");
        }else if(StringUtils.isEmpty(password)) {
            return new JsonBean<>(0,"请填写登录密码");
        }

        //校验密码
        Employee employee = employeeMapper.selectOne(new LambdaQueryWrapper<Employee>().eq(Employee::getLoginName, loginName));
        if(employee == null||employee.getDeletedFlag()==1) {
            return new JsonBean<>(0,"你输入的登录账号不存在或者已被删除，请联系管理员");
        }
        if(employee.getDisabledFlag()==1){
            return new JsonBean<>(0,"你输入的登录账号已被禁用，请联系管理员");
        }
        String encryptPassword = MD5Util.md5(password,employee.getEmployeeUid());
        if(!encryptPassword.equals(employee.getLoginPwd())){
            return new JsonBean<>(0,"密码错误");
        }

        HttpSession session=request.getSession(true);
        session.setAttribute("user_token",employee);

        // 创建Cookie，存储用户唯一标识
        Cookie userCookie = new Cookie("administrator", employee.getEmployeeUid());
        // 设置Cookie有效期为24小时（86400秒）
        userCookie.setMaxAge(86400);
        // 设置Cookie作用路径，根路径表示全站有效
        userCookie.setPath("/");
        // 设置HttpOnly属性，增强安全性，防止JS读取
        //userCookie.setHttpOnly(true);
        // 在生产环境下可以设置Secure为true，仅在HTTPS连接中传输
        // userCookie.setSecure(true);
        // 添加Cookie到响应
        response.addCookie(userCookie);

        return new JsonBean<>(1,"登录成功");
    }

    //退出登录
    public JsonBean<Void> logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return new JsonBean<>(1,"登出成功");
    }


    public IPage<EmployeeVO> selectEmployeePage(Page<Employee> page) {
        IPage<Employee> employeeIPage = employeeMapper.selectEmployeePage(page);


        Page<EmployeeVO> employeeVOPage = new Page<>(
                employeeIPage.getCurrent(),  // 当前页码
                employeeIPage.getSize(),     // 每页条数
                employeeIPage.getTotal()     // 总条数
        );

        List<EmployeeVO> employeeVOList = employeeIPage.getRecords().stream()
                .map(employee -> {
                    EmployeeVO vo = new EmployeeVO();
                    // 手动映射（推荐，避免字段冗余或类型不匹配）
                    vo.setActualName(employee.getActualName());
                    vo.setGender(employee.getGender()==0?"男":"女");
                    vo.setLoginName(employee.getLoginName());
                    vo.setPhone(employee.getPhone());
                    vo.setEmail(employee.getEmail());
                    vo.setDepartment(Department.getName(employee.getDepartmentId()));
                    vo.setPosition(Position.getName(employee.getPositionId()));
                    vo.setIdDisabled(employee.getDisabledFlag()==1?"被禁用":"启用");
                    vo.setCreateTime(employee.getCreateTime());

                    // 方式2：使用BeanUtils拷贝（适用于字段名和类型完全一致的场景）
                    // BeanUtils.copyProperties(employee, vo);

                    return vo;
                })
                .collect(Collectors.toList());

        // 4. 给新分页对象设置转换后的VO列表
        employeeVOPage.setRecords(employeeVOList);

        // 5. 返回IPage<EmployeeVO>（Page是IPage的实现类）
        return employeeVOPage;
    }




    public JsonBean<Void> addEmployee(String actualName, String gender, String loginName, String password, String phone, String email, String department, String position, String idDisabled) {
        // 基础校验
        if (!StringUtils.hasText(actualName)) return new JsonBean<>(0, "请填写姓名");
        if (!StringUtils.hasText(loginName))  return new JsonBean<>(0, "请填写登录账号");
        if (!StringUtils.hasText(password))   return new JsonBean<>(0, "请填写初始密码");
        if (!StringUtils.hasText(phone))      return new JsonBean<>(0, "请填写手机号");
        if (!StringUtils.hasText(department)) return new JsonBean<>(0, "请选择部门");
        if (!StringUtils.hasText(position))   return new JsonBean<>(0, "请选择职务");

        // 账号唯一
        long exists = this.count(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getLoginName, loginName)
                .eq(Employee::getDeletedFlag, 0));
        if (exists > 0) {
            return new JsonBean<>(0, "登录账号已存在");
        }

        // 枚举/字典转换
        Integer genderCode = "女".equals(gender) ? 1 : 0; // 0:男 1:女
        Integer disabledFlag = "禁用".equals(idDisabled) ? 1 : 0; // 0:启用 1:禁用
        Long departmentId = Department.getCode(department); // 1/2
        Long positionId   = Position.getCode(position);     // 1/2
        if (departmentId == -1) return new JsonBean<>(0, "部门选择有误");
        if (positionId == -1)   return new JsonBean<>(0, "职务选择有误");

        // 生成盐并加密密码
        String uid = java.util.UUID.randomUUID().toString();
        String encPwd = MD5Util.md5(password, uid);

        // 组装实体
        Employee e = new Employee();
        e.setEmployeeUid(uid);
        e.setActualName(actualName);
        e.setLoginName(loginName);
        e.setLoginPwd(encPwd);
        e.setGender(genderCode);
        e.setPhone(phone);
        e.setEmail(email);
        e.setDepartmentId(departmentId);
        e.setPositionId(positionId);
        e.setDisabledFlag(disabledFlag);
        e.setDeletedFlag(0);
        e.setAdministratorFlag(0);
        e.setCreateTime(LocalDateTime.now());
        e.setUpdateTime(LocalDateTime.now());

        // 保存
        this.save(e);
        return new JsonBean<>(1, "添加成功");
    }

    // 根据登录名获取员工详情
    public JsonBean<Employee> getEmployeeByLoginName(String loginName) {
        if (!StringUtils.hasText(loginName)) {
            return new JsonBean<>(0, "登录名不能为空");
        }

        Employee employee = this.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getLoginName, loginName)
                .eq(Employee::getDeletedFlag, 0));

        if (employee == null) {
            return new JsonBean<>(0, "员工不存在");
        }

        return new JsonBean<>(1, "获取成功", employee);
    }

    // 更新员工信息
    public JsonBean<Void> updateEmployee(String loginName, String actualName, String gender,
                                         String phone, String email, String department, String position,
                                         String idDisabled) {
        // 基础校验
        if (!StringUtils.hasText(loginName)) return new JsonBean<>(0, "登录名不能为空");
        if (!StringUtils.hasText(actualName)) return new JsonBean<>(0, "请填写姓名");
        if (!StringUtils.hasText(phone)) return new JsonBean<>(0, "请填写手机号");
        if (!StringUtils.hasText(department)) return new JsonBean<>(0, "请选择部门");
        if (!StringUtils.hasText(position)) return new JsonBean<>(0, "请选择职务");

        // 检查员工是否存在
        Employee existingEmployee = this.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getLoginName, loginName)
                .eq(Employee::getDeletedFlag, 0));

        if (existingEmployee == null) {
            return new JsonBean<>(0, "员工不存在");
        }

        // 枚举/字典转换
        Integer genderCode = "女".equals(gender) ? 1 : 0; // 0:男 1:女
        Integer disabledFlag = "禁用".equals(idDisabled) ? 1 : 0; // 0:启用 1:禁用
        Long departmentId = Department.getCode(department); // 1/2
        Long positionId = Position.getCode(position);     // 1/2

        if (departmentId == -1) return new JsonBean<>(0, "部门选择有误");
        if (positionId == -1) return new JsonBean<>(0, "职务选择有误");

        // 更新员工信息
        existingEmployee.setActualName(actualName);
        existingEmployee.setGender(genderCode);
        existingEmployee.setPhone(phone);
        existingEmployee.setEmail(email);
        existingEmployee.setDepartmentId(departmentId);
        existingEmployee.setPositionId(positionId);
        existingEmployee.setDisabledFlag(disabledFlag);
        existingEmployee.setUpdateTime(LocalDateTime.now());

        // 保存更新
        this.updateById(existingEmployee);
        return new JsonBean<>(1, "更新成功");
    }

    // 删除员工（软删除）
    public JsonBean<Void> deleteEmployee(String loginName) {
        if (!StringUtils.hasText(loginName)) {
            return new JsonBean<>(0, "登录名不能为空");
        }

        Employee employee = this.getOne(new LambdaQueryWrapper<Employee>()
                .eq(Employee::getLoginName, loginName)
                .eq(Employee::getDeletedFlag, 0));

        if (employee == null) {
            return new JsonBean<>(0, "员工不存在");
        }

        // 软删除
        employee.setDeletedFlag(1);
        employee.setUpdateTime(LocalDateTime.now());
        this.updateById(employee);

        return new JsonBean<>(1, "删除成功");
    }

    public JsonBean<Void> batchDeleteEmployees(List<String> loginNames) {
        if (loginNames == null || loginNames.isEmpty()) {
            return new JsonBean<>(0, "请选择要删除的员工");
        }

        // 批量软删除
        List<Employee> employees = this.list(new LambdaQueryWrapper<Employee>()
                .in(Employee::getLoginName, loginNames)
                .eq(Employee::getDeletedFlag, 0));

        if (employees.isEmpty()) {
            return new JsonBean<>(0, "未找到要删除的员工");
        }

        for (Employee employee : employees) {
            employee.setDeletedFlag(1);
            employee.setUpdateTime(LocalDateTime.now());
        }

        this.updateBatchById(employees);
        return new JsonBean<>(1, "批量删除成功");
    }

    public JsonBean<Void> changeEmployeePassword(String loginName, String newPassword) {
        try {
            // 1. 验证员工是否存在
            Employee employee = employeeMapper.selectOne(
                    new LambdaQueryWrapper<Employee>()
                            .eq(Employee::getLoginName, loginName)
                            .eq(Employee::getDeletedFlag, 0)
            );

            if (employee == null) {
                return new JsonBean<>(0, "员工不存在");
            }

            // 2. 对新密码进行加密处理
            String salt = employee.getEmployeeUid();
            String encPwd = MD5Util.md5(newPassword, salt);
            Long employeeId = employee.getEmployeeId();

            // 3. 更新密码
            Employee updateEmployee = new Employee();
            updateEmployee.setEmployeeId(employeeId);
            updateEmployee.setLoginPwd(encPwd);
            updateEmployee.setUpdateTime(LocalDateTime.now());

            int result = employeeMapper.updateById(updateEmployee);
            if (result > 0) {
                return new JsonBean<>(1, "密码修改成功");
            } else {
                return new JsonBean<>(0, "密码修改失败");
            }

        } catch (Exception e) {
            return new JsonBean<>(0, "系统异常，请稍后重试");
        }
    }

    public JsonBean<Void> verifyIdentity(String employeeUid) {
        Employee employee = employeeMapper.selectOne(
                new LambdaQueryWrapper<Employee>()
                        .eq(Employee::getEmployeeUid, employeeUid)
                        .eq(Employee::getDeletedFlag, 0)
        );
        if (employee == null) {
            return new JsonBean<>(0, "员工不存在");
        }
        if(employee.getAdministratorFlag()==1){
            return new JsonBean<>(1,"管理员登录");
        }
        return new JsonBean<>(0, "欢迎登录");
    }
}
